package com.kdgc.energy.dmm.lambda;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;

/**
 * lambda工具类
 * <p>
 * 注意：lambdaClass必须是Serializable，具体原因参见SerializedLambda文件头的注释
 * writeReplace方法亦在SerializedLambda中说明
 *
 * @author xu.wenchang
 * @version 1.0 2022/04/14
 */
public final class LambdaUtil {
    
    public static Lambda toLambda(Class<?> lambdaClass, Object obj) throws Exception {
        Method method = lambdaClass.getDeclaredMethod("writeReplace");
        method.setAccessible(true);
        Lambda lambda = new Lambda();
        SerializedLambda serializedLambda = (SerializedLambda) method.invoke(obj);
        lambda.setMethodName(serializedLambda.getImplMethodName());
        lambda.setClassName(serializedLambda.getImplClass());
        Class<?> clazz = Class.forName(serializedLambda.getImplClass()
                                                       .replaceAll("/", "."));
        lambda.setClazz(clazz);
        return lambda;
    }
}
